const Base = require('./base');
const qiniu = require('qiniu');

module.exports = class extends Base {
  async imgAction() {
    const file = this.request.body;
    const bufferData = file.file[0].data;
    let qiNiuInfo = this.createToken();
    
    function qiNiuUpload() {
      let p = new Promise((resolve, reject) => {
        let config = new qiniu.conf.Config(); // 构建一个上传用的config对象
        config.zone = qiniu.zone[saas.config.qiniu.zone]; // 空间对应的机房
        let key = saas.uuid(); //
        let formUploader = new qiniu.form_up.FormUploader(config);
        let putExtra = new qiniu.form_up.PutExtra();
        formUploader.put(qiNiuInfo.uploadToken, key, bufferData, putExtra, function (respErr, respBody, respInfo) {
          if (respErr) {
            reject(respErr)
          }
          if (respInfo && respInfo.statusCode == 200) {
            resolve(qiNiuInfo.uploadAddress + respBody.key);
          } else {
            reject(respErr)
          }
        });
      }).catch(function (error) {
        return error
      })
      return p;
    }
    
    let imgSrc = await qiNiuUpload();
    
    return this.success(imgSrc);
  }
  
  // 获取上传参数
  createToken() {
    let accessKey = saas.config.qiniu.accessKey;
    let secretKey = saas.config.qiniu.secretKey;
    let bucketName = saas.config.qiniu.bucketName;
    let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    let options = {'scope': bucketName};
    let putPolicy = new qiniu.rs.PutPolicy(options);
    let uploadToken = putPolicy.uploadToken(mac);
    return {
      uploadToken: uploadToken,
      uploadAreaCode: saas.config.qiniu.uploadAreaCode,
      uploadArea: saas.config.qiniu.uploadArea,
      uploadAddress: saas.config.qiniu.uploadAddress,
    };
  }
  
}